package file

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"iot-base/auth/config"
	types2 "iot-base/auth/types"
	"iot-base/auth/utils"
	"path"
	"path/filepath"
	"strings"
	"time"
)

//var ostype = runtime.GOOS

func UploadImg(c *gin.Context) {
	resp := types2.NewResult(c)
	f, err := c.FormFile("img")
	// 图片大小不能超过 2M
	if (float64(f.Size) / 1024) > 2048 {
		resp.ErrorCode(types2.UploadError, "图片大小不能超过2M")
		return
	}
	if err != nil {
		resp.ErrorCode(types2.UploadError, "")
		return
	} else {
		fileExt := strings.ToLower(path.Ext(f.Filename))
		if fileExt != ".png" && fileExt != ".jpg" && fileExt != ".gif" && fileExt != ".jpeg" {
			resp.ErrorCode(types2.UploadError, "上传失败!只允许png,jpg,gif,jpeg文件")
			return
		}
		fileName := utils.GetMd5(fmt.Sprintf("%s%s", f.Filename, time.Now().String()))
		filePath := filepath.Join(utils.Mkdir(config.Conf.Server.UploadPath), "/", fileName+fileExt)
		c.SaveUploadedFile(f, filePath)
		filePath = strings.Replace(filePath, "..", "", 1)
		if filePath[0:1] != "\\" {
			filePath = "/" + filePath
		}
		resp.Success(gin.H{"img_url": filePath})
	}
}
